﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Tzx.TUpdater.Entity;

namespace Tzx.TUpdater.WinBuilder
{
    /// <summary>
    /// 服务器端配置文件(tupdater.xml)生成器
    /// </summary>
    internal sealed partial class ServerConfigBuilderFrm : BaseForm //Form,BaseForm
    {
        #region 加载时

        /// <summary>
        /// 构造函数
        /// </summary>
        internal ServerConfigBuilderFrm()
        {
            InitializeComponent();

            InitializeComponent2();

            Load += new EventHandler(ServerConfigBuilderFrm_Load);

            TxtConfigContent.KeyPress += new KeyPressEventHandler(TxtConfigContent_KeyPress);

            #region 拖拽

            //支持拖拽
            TxtRootDirectory.AllowDrop = TxtIncludeFilePattern.AllowDrop = TxtExcludeFilePattern.AllowDrop = true;

            TxtRootDirectory.DragEnter += new DragEventHandler(Txt_DragEnter);
            TxtIncludeFilePattern.DragEnter += new DragEventHandler(Txt_DragEnter);
            TxtExcludeFilePattern.DragEnter += new DragEventHandler(Txt_DragEnter);

            TxtRootDirectory.DragDrop += new DragEventHandler(Txt_DragDrop);
            TxtIncludeFilePattern.DragDrop += new DragEventHandler(Txt_DragDrop);
            TxtExcludeFilePattern.DragDrop += new DragEventHandler(Txt_DragDrop);

            #endregion

        }

        /// <summary>
        /// 
        /// </summary>
        private void InitializeComponent2()
        {
            //提示信息
            ToolTipForm.SetToolTip(TxtDescription, 
@"更新描述介绍信息。"
);
            ToolTipForm.SetToolTip(TxtRootDirectory,
@"升级文件所在目录，例如：“D:\TestApp\Release\”。"
);
            ToolTipForm.SetToolTip(TxtIncludeFilePattern, 
@"若包含全部文件，请保持为空或“*”。
否则使用格式例如：“*.exe;*.dll;erp.exe;”。
文件名可用“*”，“?”替代符，多个文件请用分号“;”分隔。"
);
            ToolTipForm.SetToolTip(TxtExcludeFilePattern, 
@"若无需排除任何文件，请保持为空。
否则请使用格式例如：“web.config;*.xml;*.tmp”。
文件名可用“*”，“?”替代符，多个文件请用分号“;”分隔。"
);
            ToolTipForm.SetToolTip(TxtConfigContent, 
@""
);
        }

        /// <summary>
        /// 加载时
        /// </summary>
        private void ServerConfigBuilderFrm_Load(object sender, EventArgs e)
        {
            //
            Text = AppGlobal.AppNameText;
            //
            TxtDescription.Text = string.Format("程序更新({0})",DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
            
            //排除文件
            TxtExcludeFilePattern.Text = string.Empty;
            TxtExcludeFilePattern.Text += AppGlobal.ExeNameAndExt;
            TxtExcludeFilePattern.Text += ";" + AppGlobal.ExeName + ".xml";
            TxtExcludeFilePattern.Text += ";" + AppGlobal.ExeName + ".ini";
            TxtExcludeFilePattern.Text += ";" + AppGlobal.ExeName + ".exe.ini";
            TxtExcludeFilePattern.Text += ";" + AppGlobal.ExeName + ".log";
        }

        #endregion

        /// <summary>
        /// Ctrl+A全选
        /// </summary>
        private void TxtConfigContent_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar=='\x1') //Ctrl+A
            {
                TextBox tb = sender as TextBox;
                if (tb != null)
                {
                    tb.SelectAll();
                }
                e.Handled = true;
            }
        }

        #region 拖拽

        /// <summary>
        /// 
        /// </summary>
        private void Txt_DragEnter(object sender, DragEventArgs e)
        {
            //Debug.WriteLine("TxtFolderPath_DragEnter");
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void Txt_DragDrop(object sender, DragEventArgs e)
        {
            //string fileOrDirPath = ((System.Array) e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            string[] fileOrDirPathArray = (string[]) e.Data.GetData(DataFormats.FileDrop);
            if (fileOrDirPathArray == null || fileOrDirPathArray.Length == 0)
            {
                return;
            }
            string fileOrDirPathFirst = fileOrDirPathArray.GetValue(0).ToString();
            string dirPathFirst = string.Empty;
            if (File.Exists(fileOrDirPathFirst))
            {
                //是文件
                dirPathFirst = fileOrDirPathFirst.Substring(0, fileOrDirPathFirst.LastIndexOf('\\')).TrimEnd('\\');
            }
            else if (Directory.Exists(fileOrDirPathFirst))
            {
                //是文件夹
                dirPathFirst = fileOrDirPathFirst;
            }
            else
            {
                //都不是
            }

            //
            if (sender == TxtRootDirectory)
            {
                //1.文件所在目录
                TxtRootDirectory.Text = dirPathFirst;
            }
            else if (sender == TxtIncludeFilePattern || sender == TxtExcludeFilePattern)
            {
                //2.3.
                TextBox tb = sender as TextBox;
                if (tb != null)
                {
                    foreach (string s in fileOrDirPathArray)
                    {
                        string fileName = s.Substring(s.LastIndexOf('\\')).TrimStart('\\');
                        string text = tb.Text.Trim().Replace(' '.ToString(), string.Empty);
                        int index0 = text.IndexOf(fileName, StringComparison.CurrentCultureIgnoreCase);
                        int index1 = text.IndexOf(fileName + ";", StringComparison.CurrentCultureIgnoreCase);
                        int index2 = text.IndexOf(";" + fileName, StringComparison.CurrentCultureIgnoreCase);
                        if (index0 == -1 && index1 == -1 && index2 == -1)
                        {
                            tb.Text = (tb.Text + ";" + fileName).Trim(';');
                        }
                    }
                }
            }
            else
            {
                //
            }
        }

        #endregion

        /// <summary>
        /// 按钮:文件夹选择
        /// </summary>
        private void BtnShowFolderSelectDialog_Click(object sender, EventArgs e)
        {
            string path = TxtRootDirectory.Text.Trim();
            string openPath = null;
            if (!string.IsNullOrEmpty(path))
            {
                if (File.Exists(path))
                {
                    //是文件
                    openPath = path.Substring(0, path.LastIndexOf('\\')).TrimEnd('\\');
                }
                else if (Directory.Exists(path))
                {
                    //是文件夹
                    openPath = path;
                }
                else
                {
                    //都不是
                    openPath = string.Empty;
                }
            }

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (!string.IsNullOrEmpty(openPath) && Directory.Exists(openPath))
            {
                dialog.SelectedPath = openPath;
            }
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                TxtRootDirectory.Text = foldPath;
            }
        }

        /// <summary>
        /// 按钮:生成
        /// </summary>
        private void BtnBuilder_Click(object sender, EventArgs e)
        {
            string rootDir = TxtRootDirectory.Text = TxtRootDirectory.Text.Trim();
            string includePattern = TxtIncludeFilePattern.Text = TxtIncludeFilePattern.Text.Trim();
            string excludePattern = TxtExcludeFilePattern.Text = TxtExcludeFilePattern.Text.Trim();
            SearchOption so;
            if (RbtnAllDirectories.Checked)
            {
                so = SearchOption.AllDirectories;
            }
            else if (RbtnTopDirectoryOnly.Checked)
            {
                so = SearchOption.TopDirectoryOnly;
            }
            else
            {
                MessageBox.Show(string.Format("搜索选项只能是 [当前目录] 或 [当前目录及所有子目录]"),Text,MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            if(string.IsNullOrEmpty(rootDir))
            {
                MessageBox.Show(string.Format("请选择待更新文件所在目录"), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                TxtRootDirectory.Focus();
                return;
            }

            //开始生成
            List<string> fileList = ServerConfigBuilder.GetUpdateFiles(rootDir, includePattern, excludePattern, so);
            List<UpdateItem> uFileList = new List<UpdateItem>();
            foreach (string file in fileList)
            {
                UpdateItem uf = XmlConfig.GetUpdateFile(rootDir, file);
                if (uf != null)
                {
                    uFileList.Add(uf);
                }
            }

            string xmlText = XmlConfig.CreateUpdateXmlString(TxtDescription.Text.Trim(), uFileList);
            TxtConfigContent.Text = xmlText;
        }

        /// <summary>
        /// 按钮:保存到文件
        /// </summary>
        private void BtnSave_Click(object sender, EventArgs e)
        {
            string xmlText = TxtConfigContent.Text = TxtConfigContent.Text.Trim();
            if (string.Empty == xmlText)
            {
                MessageBox.Show("没有内容，不能保存！",Text,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                return;
            }

            //保存
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "txt files (*.xml)|*.xml|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.InitialDirectory = TxtRootDirectory.Text;
            saveFileDialog1.FileName = AppGlobal.ExeName + ".xml";
            saveFileDialog1.RestoreDirectory = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog1.FileName, xmlText, Encoding.UTF8);
            }
        }

        /// <summary>
        /// 按钮:退出
        /// </summary>
        private void BtnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

    }
}